﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CustomJwtAuthorizationSample.Extensions;
using CustomJwtAuthorizationSample.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace CustomJwtAuthorizationSample
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940

        public Startup(IConfiguration configuration)
        {
            this._configuration = configuration;
        }
        private readonly IConfiguration _configuration;
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<JwtSettings>(_configuration.GetSection("JwtSettings"));
            var jwtSettings = new JwtSettings();
            _configuration.Bind("JwtSettings", jwtSettings);

            services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(opt =>
            {
                //opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                //{
                //    ValidIssuer = jwtSettings.Issuer,
                //    ValidAudience = jwtSettings.Audience,
                //    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
                //};
                opt.SecurityTokenValidators.Clear();
                opt.SecurityTokenValidators.Add(new JwtTokenValidator());
                opt.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = ctx => {
                        var tokens = ctx.Request.Headers["myToken"];
                        ctx.Token = tokens.FirstOrDefault();
                        return Task.CompletedTask;
                    }
                };
            });

            services.AddMvc();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}
